package com.imyours.webservice.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imyours.model.user.UserEntity;
import com.imyours.users.session.UserSessionManager;

public abstract class ContextService implements Service {

	protected Context context = null;

	protected final Logger logger = LoggerFactory.getLogger("Service");

	public ContextService(Context context) {
		this.context = context;
	}

	public Context getContext() {
		return this.context;
	}

	/**
	 * 验证sessionId有效性
	 * 
	 * @return
	 * @throws Exception
	 */
	protected UserEntity getUserEntity() {
		String sessionId = context.getParameter().get("sessionId");
		UserEntity user = UserSessionManager.getInstance().getUser(sessionId);
		logger.info("userENtity:" + user);
		if (user == null) {
			context.fail(2, "invalidate sessionId");
		}
		return user;
	}

	/**验证是否拥有管理员权限
	 * @return
	 */
	protected boolean isAdmin() {
		boolean result = false;
		UserEntity user = getUserEntity();
		if (user != null) {
			result = user.isAdmin();
			if (result == false) {
				context.fail(5, "has no privilege");
			}
		}
		return result;
	}

}
